package com.cloud.example.config.tx;

import com.cloud.async.flow.web.tx.TransactionSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * JPA版本手动控制事务： 测试通过
 *
 * @author chengrui
 */
@Component
public class JpaTransactionSourceFlow implements TransactionSource {

    @Autowired
    private PlatformTransactionManager transactionManager;


    @Override
    public boolean commitTrans(Object transactionObj) {
        TransactionStatus transaction = (TransactionStatus) transactionObj;
        transactionManager.commit(transaction);
        return true;
    }



    @Override
    public boolean rollBack(Object transactionObj) {
        TransactionStatus transaction = (TransactionStatus) transactionObj;
        transactionManager.rollback(transaction);
        return true;
    }


    @Override
    public  TransactionStatus newSession(){
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        return status;
    }

}
